package com.example.book.common.utils;

import com.example.book.domain.sys.SysMenu;

import java.util.ArrayList;
import java.util.List;

/**
 * 树形菜单
 * @author pangxichen
 */
public class MenuUtil {

    public static List<SysMenu> rootTree(List<SysMenu> list){

        List<SysMenu> root = new ArrayList<>();
        for (SysMenu sysMenu:list){
            if (null == sysMenu.getParentId() || "".equals(sysMenu.getParentId())){
                root.add(sysMenu);
            }
        }

        for (SysMenu sysMenu:root){
            List<SysMenu> children = children(sysMenu.getId(),list);
            sysMenu.setSysMenus(children);
        }

        return root;
    }

    private static List<SysMenu> children(String id,List<SysMenu> list){
        List<SysMenu> childList = new ArrayList<>();
        for (SysMenu sysMenu : list) {
            if (sysMenu.getParentId().equals(id)) {
                childList.add(sysMenu);
            }
        }
        for (SysMenu sysMenu : childList) {
            sysMenu.setSysMenus(children(sysMenu.getId(), list));
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

}
